package com.wzg.appframe.web;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.os.TestLooperManager;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;

import com.mf.ui.skeleton.Skeleton;
import com.mf.ui.skeleton.SkeletonScreen;
import com.wzg.appframe.R;
import com.wzg.appframe.action.BaseAction;
import com.wzg.appframe.action.WebAction;
import com.wzg.appframe.utils.TLog;
import com.wzg.appframe.utils.ToastUtil;
import com.wzg.appframe.view.BaseActivity;
import com.wzg.appframe.view.SettingActivity;
import com.wzg.appframe.web.jsbridge.BridgeWebView;
import com.wzg.appframe.web.jsbridge.JavaSctiptMethods;
import com.wzg.appframe.web.local.LocalResInit;

import java.lang.ref.WeakReference;

public class BaseWebActivity extends BaseActivity {

    public static final String TAG = "BaseWebActivity";
    public static final String PAGE = "TargetUrl";

    BridgeWebView webView;
    String TargetUrl;
    WebSettings webSettings;
    JavaSctiptMethods javaSctiptMethods;
    boolean isLoadFinish = false;
    WebAction webAction;

    private SkeletonScreen skeletonScreen;
    private static final String PARAMS_TYPE = "params_type";
    public static final String TYPE_IMG_LOADING = "type_img";
    public static final String TYPE_VIEW = "type_view";

    public static void start(Context context, String type,String h5PageUrl) {
        Intent intent = new Intent(context, BaseWebActivity.class);
        intent.putExtra(PARAMS_TYPE, type);
        intent.putExtra(BaseWebActivity.PAGE, h5PageUrl);
        context.startActivity(intent);
    }

    public static class MyHandler extends android.os.Handler {
        private final WeakReference<BaseWebActivity> activityWeakReference;

        MyHandler(BaseWebActivity activity) {
            this.activityWeakReference = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (activityWeakReference.get() != null) {
                activityWeakReference.get().skeletonScreen.hide();
            }
        }
    }

    public Handler timeOutHandler ;

    public void initViews() {
        setContentView(R.layout.activity_base_web);
        String mType = getIntent().getStringExtra(PARAMS_TYPE);
        View rootView = findViewById(R.id.rootView);
        webView = findViewById(R.id.webview);
        webView.addBridgeInterface(new JavaSctiptMethods(BaseWebActivity.this, webView));//设置js和android通信桥梁方法

        if (TYPE_VIEW.equals(mType)) {

            skeletonScreen = Skeleton.bind(rootView)
                    .load(R.layout.activity_view_skeleton)
                    .duration(1000)
                    .color(R.color.shimmer_color)
                    .angle(0)
                    .show();
        }
        if (TYPE_IMG_LOADING.equals(mType)) {
            skeletonScreen = Skeleton.bind(rootView)
                    .load(R.layout.layout_img_skeleton)
                    .duration(1000)
                    .color(R.color.shimmer_color_for_image)
                    .show();
        }
    }

    public void initData() {
        //设置5秒超时时间
        timeOutHandler = new Handler();
        timeOutHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if(webView.getProgress()<100){
                    webView.stopLoading();
                }
                webAction.setSharedPreferenData("ERR_URL", webAction.getSharedPreferenData(WebAction.APP_H5_URL));
                Intent intent = new Intent(getBaseContext(), SettingActivity.class);
                startActivity(intent);
                finish();//关闭页面
                ToastUtil.show("加载页面超时，请检查地址是否正确！");
            }
        },5000);//


        webAction = new WebAction(this);
        TargetUrl = getIntent().getStringExtra(PAGE);
        webViewSetting();
        initWebCliet();
//        webView.loadUrl(TargetUrl);
//        String url = "file://"+LocalResInit.h5Path + "/" + TargetUrl;
        TLog.d("tracy TargetUrl=" + TargetUrl);
        webView.loadUrl(TargetUrl);
    }

    public void webViewSetting() {
        webSettings = webView.getSettings();
        //如果访问的页面中要与Javascript交互，则webview必须设置支持Javascript

        String loaclUA = webSettings.getUserAgentString();
        webSettings.setUserAgentString(loaclUA + " " + "NewHopeJS/Vue_1.0.0");
        webSettings.setJavaScriptEnabled(true);
        // 若加载的 html 里有JS 在执行动画等操作，会造成资源浪费（CPU、电量）
        // 在 onStop 和 onResume 里分别把 setJavaScriptEnabled() 给设置成 false 和 true 即可

        ////支持插件
        //        webSettings.setPluginsEnabled(true);

        //设置自适应屏幕，两者合用
        webSettings.setUseWideViewPort(true); //将图片调整到适合webview的大小
        webSettings.setLoadWithOverviewMode(true); // 缩放至屏幕的大小

        //缩放操作
        webSettings.setSupportZoom(true); //支持缩放，默认为true。是下面那个的前提。
        webSettings.setBuiltInZoomControls(true); //设置内置的缩放控件。若为false，则该WebView不可缩放
        webSettings.setDisplayZoomControls(false); //隐藏原生的缩放控件



        //其他细节操作
        webSettings.setCacheMode(WebSettings.LOAD_DEFAULT); //默认缓存使用模式
        webSettings.setAllowFileAccess(true); //设置可以访问文件
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true); //支持通过JS打开新窗口
        webSettings.setLoadsImagesAutomatically(true); //支持自动加载图片
        webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_COMPATIBILITY_MODE);//http,https 混合模式开启
        webSettings.setDefaultTextEncodingName("utf-8");//设置编码格式
        javaSctiptMethods = new JavaSctiptMethods(this, webView);
        webView.addBridgeInterface(javaSctiptMethods);

    }

    void initWebCliet() {
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                showDialog("页面加截中...");
                isLoadFinish = false;
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                hideDialog();
                isLoadFinish = true;
                timeOutHandler.removeCallbacksAndMessages(null);
                MyHandler myHandler = new MyHandler(BaseWebActivity.this);
                myHandler.sendEmptyMessageDelayed(1, 100);
            }

            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                super.onReceivedError(view, request, error);
                TLog.d("页面加载失败! 错误信息=" + error.getDescription() + " 错误码=" + error.getErrorCode());
                ToastUtil.show("页面加载失败! 错误信息=" + error.getDescription() + " 错误码=" + error.getErrorCode());
                //清除H5地址
//                webAction.setSharedPreferenData(WebAction.APP_H5_URL, "");
                webAction.setSharedPreferenData("ERR_URL", webAction.getSharedPreferenData(WebAction.APP_H5_URL));
                Intent intent = new Intent(getBaseContext(), SettingActivity.class);
                startActivity(intent);
                finish();//关闭页面
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        webSettings.setJavaScriptEnabled(true);
    }

    @Override
    protected void onStart() {
        super.onStart();
        javaSctiptMethods.onStart();
    }

    @Override
    protected void onStop() {
        super.onStop();
        webSettings.setJavaScriptEnabled(false);
        javaSctiptMethods.onStop();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        javaSctiptMethods.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        javaSctiptMethods.onDestroy();
    }

    @Override
    public void onBackPressed() {
        if (isLoadFinish) {
            webView.post(new Runnable() {
                @Override
                public void run() {
                    webView.loadUrl("javascript:onBackPressed()");
                }
            });
        } else {
            super.onBackPressed();
        }

    }
}
